import React, { PureComponent } from "react";
import { connect } from "dva";
import router from "umi/router";
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  InputNumber,
  Radio,
  Icon,
  Tooltip,
  message
} from "antd";
// import Upload from "../../components/Upload";
import PageHeaderLayout from "../../layouts/PageHeaderLayout";
import { getUserInfo }  from '../../utils/request';



const FormItem = Form.Item;
const { Option } = Select;

const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
};

const beforeUpload = file => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJPG) {
    message.error("仅允许上传JPG、PNG文件!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片文件不能大于2MB!");
  }
  return isJPG && isLt2M;
};

@connect(({ user, global }) => ({
  user:user,
  UserInfo: global.currentUser
}))
@Form.create()
export default class BasicForms extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      imageUrl: this.props.UserInfo.avatar,
      loading: false
    };
  }

  componentDidMount() {
    // this.props.dispatch({
    //   type: 'user/fetchCurrentUser',
    // }).then(() => {
    //
    //   this.setState({
    //     imageUrl: this.props.user.currentUser.avatar
    //   });
    //
    // });
  }

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // if(values.email==""){
        //   delete values.email;
        // }
        // if(values.email!=undefined || values.avatar!=undefined){
        this.props.dispatch({
          type: "user/submitUserInfoForm",
          payload: {
            ...values,
            username:undefined,
          }
        });
        // }
      }
    });
  };

  handleChange = info => {
    if (info.file.status === "uploading") {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      // info.fileList.splice(0,info.fileList.length-1);
      getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading: false
        })
      );
    }
  };

  handleReset = () => {
    this.props.form.resetFields();
  };

  handleTabChange = key => {
    const { dispatch } = this.props;
    switch (key) {
      case "setting":
        router.push("/personal/setting");
        break;
      case "modifypsw":
        router.push("/personal/modifypsw");
        break;
      default:
        break;
    }
  };

  normFile = e => {
    console.log("Upload event:", e);
    if (Array.isArray(e)) {
      return e;
    }

    // return e && e.fileList;
    const filelist = e && e.file;
    if (
      filelist.response &&
      filelist.response.data &&
      filelist.response.data.file_id
    ) {
      return filelist.response.data.file_id;
    } else {
      return null;
    }
  };

  render() {
    const {
      user: { currentUser, loading, submitting },
    } = this.props;
    const { getFieldDecorator, getFieldValue } = this.props.form;

    const UserInfo =getUserInfo();

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 }
      }
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 }
      }
    };

    const tabDefaultKeys = "setting";

    const tabList = [
      {
        key: "setting",
        tab: "基本设置"
      },
      {
        key: "modifypsw",
        tab: "修改密码"
      }
    ];

    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? "loading" : "plus"} />
        <div className="ant-upload-text">上传头像</div>
      </div>
    );

    const imageUrl = this.state.imageUrl;

    return (
      <PageHeaderLayout
        title="基本设置"
        tabList={tabList}
        tabActiveKey={tabDefaultKeys}
        onTabChange={this.handleTabChange}
      >
        <div>
          <Card bordered={false} bodyStyle={{ padding: "50px 25%" }}>
            <Form
              onSubmit={this.handleSubmit}
              hideRequiredMark
              style={{ marginTop: 8 }}
            >
            {/*
              <FormItem
                {...formItemLayout}
                label="头像"
                extra="支持jpg、png图片，大小不超过2M"
              >
                {getFieldDecorator("avatar", {
                  valuePropName: "file",
                  getValueFromEvent: this.normFile
                })(
                  <Upload
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    beforeUpload={beforeUpload}
                    onChange={this.handleChange}
                  >
                    {imageUrl ? (
                      <img
                        src={imageUrl}
                        alt=""
                        style={{ width: 100, height: 100 }}
                      />
                    ) : (
                      uploadButton
                    )}
                  </Upload>
                )}
              </FormItem>
            */}


              <FormItem {...formItemLayout} label="用户名称">
                {getFieldDecorator("username", {
                  initialValue: UserInfo.username,
                  rules: [
                    {
                      required: true,
                      message: "请输入用户名称"
                    }
                  ]
                })(<Input placeholder="请输入用户名称"  disabled={true}/>)}
              </FormItem>

              {/*
            <FormItem
              {...formItemLayout}
              label="部门角色"
            >
              {getFieldDecorator('role', {
                initialValue:currentUser.role,
                rules: [{
                  required: true, message: '请输入部门角色',
                }],
              })(
                <Input placeholder="您在部门的职位" />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="真实姓名">
                {getFieldDecorator("realName", {
                  initialValue: UserInfo.realName,
                  rules: [
                    {
                      required: true,
                      message: "请输入真实姓名"
                    }
                  ]
                })(<Input />)}
              </FormItem>

             */}


              <FormItem {...formItemLayout} label="手机号">
                {getFieldDecorator("mobile", {
                  initialValue: UserInfo.mobile,
                  rules: [
                    {
                      required: true,
                      pattern: /^1[34578]\d{9}$/,
                      message: "手机号格式不正确"
                    }
                  ]
                })(<Input style={{ width: "100%" }}  />)}
              </FormItem>

              <FormItem {...formItemLayout} label="E-mail">
                {getFieldDecorator("email", {
                  initialValue: UserInfo.email,
                  rules: [
                    {
                      type: "email",
                      message: "输入的E-mail格式不正确"
                    }
                  ]
                })(<Input />)}
              </FormItem>

              <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
                <Button style={{ marginRight: 8 }} onClick={this.handleReset}>
                  重置
                </Button>
                <Button type="primary" htmlType="submit" loading={loading.model_submit}>
                  提交
                </Button>
              </FormItem>
            </Form>
          </Card>
        </div>
      </PageHeaderLayout>
    );
  }
}
